package com.nulstudio.sppm.Interceptor;

import com.nulstudio.sppm.Annotation.ManagerJwt;
import com.nulstudio.sppm.Utils.JwtUtils;
import com.nulstudio.sppm.Utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class ManagerJwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = RequestUtils.getCurrentToken(request);

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(ManagerJwt.class)) {
            ManagerJwt managerJwt = method.getAnnotation(ManagerJwt.class);
            if (managerJwt.required()) {

                if (token.isEmpty()) {
                    throw new RuntimeException("no token for access");
                }
                String userAuthority = JwtUtils.getUserAuthority(token);
                if(userAuthority == null || userAuthority.equals("manager")){
                    throw new RuntimeException("no authority for the function");
                }

                String userId = JwtUtils.getUserId(token);
                log.info("用户id: {}", userId);

                JwtUtils.checkSign(token);
            }
        }
        return true;
    }
}
